import {service} from '@/config/axios'
import {ElLoading, ElMessage} from 'element-plus'
import {blobValidate} from '.'
import {saveAs} from 'file-saver'
import {useCache} from '@/hooks/web/useCache'
// 通用下载方法
const {wsCache} = useCache()
const token = wsCache.get('token') || '' //存储Token
export function download(url: string, params, filename: string) {
    let downloadLoadingInstance: any = ''
    downloadLoadingInstance = ElLoading.service({
        text: '正在下载数据，请稍候',
        background: 'rgba(0, 0, 0, 0.7)'
    })
    return service
        .post(url, params, {
            transformRequest: [
                (params) => {
                    return params
                }
            ],
            headers: {'Content-Type': 'application/x-www-form-urlencoded', Authorization: token},
            responseType: 'blob'
        })
        .then(async (data: any) => {
            const isLogin = await blobValidate(data)
            if (isLogin) {
                const blob = new Blob([data])
                saveAs(blob, filename)
            } else {
                const resText = await data.text()
                const rspObj = JSON.parse(resText)
                const errMsg = rspObj.msg
                ElMessage.error(errMsg)
            }
            downloadLoadingInstance.close()
        })
        .catch((r) => {
            console.error(r)
            ElMessage.error('下载文件出现错误，请联系管理员！')
            downloadLoadingInstance.close()
        })
}
